<?php
class User_Controller extends Base_Controller
{
    public $restful = true;

    public function get_login($redirect = '/')
    {
        return View::make('user.login')
            ->with('pageTitle', __('title.login'));
    }

    public function post_login($redirect = '/')
    {
        $credentials = array(
            'username' => Input::get('usr'),
            'password' => Input::get('pwd'),
        );

        if (Auth::attempt($credentials)) {
            return Redirect::to($redirect);
        } else {
            #return View::make('user.login')->with('error', 'Sai tên đăng nhập hoặc mật khẩu');
            return Redirect::to(URI::current())->with('error', __('m.login.failed'));
        }
    }

    public function get_logout()
    {
        Auth::logout();
        return Redirect::to('/');
    }

    public function get_channels()
    {
        if (Auth::guest())
        {
            return Redirect::to_action('user@login', array(URI::current()));
        }

        foreach (weekdays() as $key => $str)
        {
            $selChannel = Auth::user()->prichannels()->where_weekday($key)->first();
            if (!is_null($selChannel)) {
                $selChannel = $selChannel->channel_id;
            }

            $channels = Result::channelsByWeekday($key);

            $data[$key] = array(
                'name' => $str,
                'channel_selected' => $selChannel,
                'channels' => $channels
            );
        }

        $pageTitle = __('title.select-channel');

        return View::make('user.channels', compact('data', 'pageTitle'));

    }

    public function post_channels()
    {
        foreach (Config::get('weekday') as $wkKey => $wkName)
        {
            Prichannel::insertOrUpdate(array(
                'weekday' => $wkKey,
                'channel_id' => Input::get('wk_' . $wkKey),
                'user_id' => Auth::user()->id,
            ));
        }

        return Redirect::to(URI::current())
            ->with('msg', date('d/m H:i:s | ') . __('m.channel.update-success'));
    }

    public function get_collections()
    {
        return View::make('user.collections')
            ->with('pageTitle', __('title.collection'));
    }
}